package cn.com.elitecrm.util;

import java.text.SimpleDateFormat;
import java.util.Date;

public class StringUtil {
	public static String parseNull(Object source){
		if(source!=null){
			return source.toString();
		}
		return "";
	}
	
	public static String substrByBytes(String source , int maxLength, int byteLength){
		String result = source;
		if(source!=null){
			int length = maxLength>source.length()?source.length():maxLength;
			result = source.substring(0, length);
			int exceedLength = getStringBytesLength(result,byteLength) - maxLength;
			while(exceedLength>0){
				int temp = exceedLength/byteLength + (exceedLength%byteLength)>0?1:0;
				length = length - temp;
				result = result.substring(0, length);
				exceedLength = getStringBytesLength(result,byteLength) - maxLength;
			}
		}
		return result;
	}
	
	public static int getStringBytesLength(String source,int byteLength){
		String replacement = "";
		for(int i=0;i<byteLength;i++){
			replacement += "x";
		}
		return source.replaceAll("[^\\x00-\\xff]", replacement).length();
	}
	
	public static String getDateStr(long time){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(new Date(time));
	}

}
